package com.startx.core.system.model;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class ChannelFactory {
	
	 //存放所有的ChannelHandlerContext
    private static final Map<String, ChannelHandlerContext> CTX_BY_ID = new ConcurrentHashMap<String, ChannelHandlerContext>() ;
    
    //存放某一类的channel
    private static final ChannelGroup ALL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	
    
    public static void login(String key,ChannelHandlerContext ctx) {
    	
    	if(!CTX_BY_ID.containsKey(key)) {
    		CTX_BY_ID.put(key, ctx);
    		ALL_GROUP.add(ctx.channel());
    	}
    	
    }
    
    public static ChannelHandlerContext getByKey(String key) {
    	return CTX_BY_ID.get(key);
    }
    
    public static boolean isLogin(String key) {
    	return CTX_BY_ID.containsKey(key);
    }
    
    public static void logout(ChannelHandlerContext ctx) {
    	for (String key : CTX_BY_ID.keySet()) {

			if (ctx.equals(CTX_BY_ID.get(key))) {
				CTX_BY_ID.remove(key);
			}
		}
		
    	ALL_GROUP.remove(ctx.channel());
    }

    /**
     * 获取管道组
     * @return
     */
	public static ChannelGroup getGroup() {
		return ALL_GROUP;
	}

	/**
	 * 关闭连接
	 */
	public static void close() {
		ALL_GROUP.close();
		CTX_BY_ID.clear();
	}
    
}
